#include "utils.h"

char toHex(char c) {
    char mask;
    switch ((int)c) {
      case (int)'0':
        mask = 0;
        break;
      case (int)'1':
        mask = 1;
        break;
      case (int)'2':
        mask = 2;
        break;
      case (int)'3':
        mask = 3;
        break;
      case (int)'4':
        mask = 4;
        break;
      case (int)'5':
        mask = 5;
        break;
      case (int)'6': 
        mask = 6;
        break;
      case (int)'7': 
        mask = 7;
        break;
      case (int)'8': 
        mask = 8;
        break;
      case (int)'9': 
        mask = 9;
        break;
      case (int)'a': 
      case (int)'A': 
        mask = 10;
        break;
      case (int)'b': 
      case (int)'B': 
        mask = 11;
        break;
      case (int)'c': 
      case (int)'C': 
        mask = 12;
        break;
      case (int)'d': 
      case (int)'D': 
        mask = 13;
        break;
      case (int)'e': 
      case (int)'E': 
        mask = 14;
        break;
      case (int)'f': 
      case (int)'F': 
        mask = 15;
        break;
      default:
        mask = -1;
        break;
    }

    return mask;
}

int stringToHex(char *arg)
{
	int val = 0x00;
	char hex;
	int i = 0;
	char c;
	
    while(1) {
		c = arg[i];
		if(c == '\0') {
			break;
		}
		
		hex = toHex(c);
		if(hex > 0 && (hex != 0xff)) {
			val <<= 4;
			val |= hex;
		} else if(hex == 0xff) {
			return -1;
		}
		i++;
	}
	return val;
}

